<template>
  <div class="comparison-analysis">
    <!-- Filter Card -->
    <div class="search-card">
      <div class="search-section">
        <div class="filter-item">
          <label>调查期 1</label>
          <el-cascader v-model="queryParams.period1" :options="periodOptions"
            :props="{ multiple: false, emitPath: false }" placeholder="请选择调查期1" clearable class="custom-select" style="width: 200px" />
        </div>

        <div class="filter-item">
          <label>调查期 2</label>
          <el-cascader v-model="queryParams.period2" :options="periodOptions"
            :props="{ multiple: false, emitPath: false }" placeholder="请选择调查期2" clearable class="custom-select" style="width: 200px" />
        </div>

        <div class="filter-item">
          <label>分析维度</label>
          <el-select v-model="queryParams.groupBy" placeholder="请选择分析维度" class="custom-select" style="width: 180px">
            <el-option label="全省汇总" value="" />
            <el-option label="按地区" value="region" />
            <el-option label="按性质" value="nature" />
            <el-option label="按行业" value="industry" />
          </el-select>
        </div>

        <div class="filter-item">
          <label>展示模式</label>
          <el-select v-model="displayMode" placeholder="请选择展示模式" class="custom-select" style="width: 160px">
            <el-option label="企业数量" value="enterprise" />
            <el-option label="岗位数量" value="position" />
            <el-option label="失业率" value="ratio" />
          </el-select>
        </div>

        <div class="filter-actions">
          <el-button type="primary" class="btn-primary-theme" @click="handleQuery" :loading="loading">
            对比
          </el-button>
        </div>
      </div>
    </div>

    <!-- Stats Grid -->
    <div class="stats-grid" v-if="stats.period1 && stats.period2">
      <div class="stat-card">
        <div class="stat-label">{{ period1Name }} {{ getStatLabel() }}</div>
        <div :class="getStatValueClass(stats.period1.value)">{{ formatStatValue(stats.period1.value) }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">{{ period2Name }} {{ getStatLabel() }}</div>
        <div :class="getStatValueClass(stats.period2.value)">{{ formatStatValue(stats.period2.value) }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">变化趋势</div>
        <div :class="getTrendClass()">
          {{ stats.trend > 0 ? '↑' : '↓' }} {{ formatTrendValue() }}
        </div>
      </div>
    </div>

    <!-- Chart Card -->
    <div class="chart-card" v-if="chartData.dimensions.length > 0">
      <div class="card-header">
        <span class="card-title">{{ chartTitle }}</span>
      </div>
      <div class="chart-wrapper">
        <div ref="chartRef" class="chart-container" :style="{ height: chartHeight + 'px' }"></div>
        <div class="legend">
          <div class="legend-item">
            <div class="legend-color" style="background: #4f46e5"></div>
            <span>{{ period1Name }}</span>
          </div>
          <div class="legend-item">
            <div class="legend-color" style="background: #10b981"></div>
            <span>{{ period2Name }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- Table Card -->
    <div class="table-card" v-if="tableData.length > 0">
      <div class="card-header">
        <span class="card-title">对比数据详情</span>
      </div>
      <el-table :data="tableData" class="modern-table"
        :header-cell-style="{ background: '#f8fafc', color: '#475569', fontWeight: '700', fontSize: '13px', height: '56px', textAlign: 'center' }"
        :cell-style="{ textAlign: 'center', padding: '12px 0' }">
        <el-table-column prop="dimensionName" label="维度" align="center" fixed min-width="180">
          <template #default="{ row }">
            <span class="cell-primary-text">{{ row.dimensionName }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="period1Name" align="center">
          <template v-if="displayMode === 'enterprise'">
            <el-table-column prop="period1.enterpriseCount" label="企业数" align="center" />
          </template>
          <template v-else-if="displayMode === 'position'">
            <el-table-column prop="period1.constructionTotal" label="建档期岗位" align="center" />
            <el-table-column prop="period1.investigationTotal" label="调查期岗位" align="center" />
          </template>
          <template v-else>
            <el-table-column prop="period1.changeRatio" label="失业率(%)" align="center">
              <template #default="{ row }">
                {{ row.period1.changeRatio.toFixed(2) }}%
              </template>
            </el-table-column>
          </template>
        </el-table-column>
        <el-table-column :label="period2Name" align="center">
          <template v-if="displayMode === 'enterprise'">
            <el-table-column prop="period2.enterpriseCount" label="企业数" align="center" />
          </template>
          <template v-else-if="displayMode === 'position'">
            <el-table-column prop="period2.constructionTotal" label="建档期岗位" align="center" />
            <el-table-column prop="period2.investigationTotal" label="调查期岗位" align="center" />
          </template>
          <template v-else>
            <el-table-column prop="period2.changeRatio" label="失业率(%)" align="center">
              <template #default="{ row }">
                {{ row.period2.changeRatio.toFixed(2) }}%
              </template>
            </el-table-column>
          </template>
        </el-table-column>
        <el-table-column label="变化" align="center">
          <template #default="{ row }">
            <span :class="getDiffClass(row.diff)" class="diff-value">
              {{ formatDiff(row.diff) }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- Empty State -->
    <div v-if="!loading && tableData.length === 0" class="empty-card">
      <el-empty description="请选择两个调查期和分析维度后查询" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import dataAnalysisApi from '@/api/dataAnalysis';
import periodApi from '@/api/period';

// ... (script logic remains exactly the same) ...
// ==================== 数据定义 ====================

const loading = ref(false);
const chartRef = ref(null);
let chartInstance = null;

// 查询参数
const queryParams = ref({
  period1: null,
  period2: null,
  groupBy: 'region',
});

// 展示模式: 'enterprise' | 'position' | 'ratio'
const displayMode = ref('ratio');

// 调查期列表
const periodList = ref([]);

const periodOptions = computed(() => {
  const groups = {};

  periodList.value.forEach(period => {
    const name = period.investigateTime || '';
    const yearMatch = name.match(/^(\d{4})/);
    const year = yearMatch ? yearMatch[1] : '其他';

    if (!groups[year]) {
      groups[year] = [];
    }

    let monthLabel = name;
    if (year !== '其他') {
      monthLabel = name.replace(year, '').replace(/^[年-]/, '');
    }

    groups[year].push({
      value: period.periodId,
      label: monthLabel
    });
  });

  return Object.keys(groups)
    .sort((a, b) => b.localeCompare(a))
    .map(year => ({
      value: year,
      label: year === '其他' ? '其他' : `${year}年`,
      children: groups[year]
    }));
});

// 统计数据
const stats = ref({
  period1: null,
  period2: null,
  trend: 0,
});

// 图表数据
const chartData = ref({
  dimensions: [],
  period1Data: [],
  period2Data: [],
});

const BAR_WIDTH = 26;
const BAR_GAP_RATIO = 0.1;
const BAR_CATEGORY_GAP_RATIO = 10;
const MIN_CHART_HEIGHT = 360;
const HEIGHT_PER_ITEM = 82;

const chartHeight = computed(() => {
  const count = chartData.value.dimensions?.length || 0;
  if (count === 0) return MIN_CHART_HEIGHT;
  return Math.max(MIN_CHART_HEIGHT, count * HEIGHT_PER_ITEM);
});

// 表格数据
const tableData = ref([]);

// ==================== 计算属性 ====================

const period1Name = computed(() => {
  const period = periodList.value.find(p => p.periodId === queryParams.value.period1);
  return period ? period.investigateTime : '调查期1';
});

const period2Name = computed(() => {
  const period = periodList.value.find(p => p.periodId === queryParams.value.period2);
  return period ? period.investigateTime : '调查期2';
});

const chartTitle = computed(() => {
  const titles = {
    enterprise: '企业数量对比',
    position: '岗位数量对比',
    ratio: '失业率对比',
  };
  return titles[displayMode.value] || '数据对比';
});

// ==================== 生命周期 ====================

onMounted(async () => {
  await loadPeriodList();
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener('resize', handleResize);
});

// 监听展示模式变化
watch(displayMode, () => {
  if (tableData.value.length > 0) {
    // 根据新的展示模式重新计算图表数据
    const getValue = (item) => {
      switch (displayMode.value) {
        case 'enterprise':
          return item.enterpriseCount;
        case 'position':
          return item.investigationTotal;
        case 'ratio':
        default:
          return item.changeRatio;
      }
    };

    // 更新差值
    tableData.value = tableData.value.map(row => ({
      ...row,
      diff: getValue(row.period2) - getValue(row.period1)
    }));

    // 更新图表数据
    chartData.value = {
      dimensions: tableData.value.map(item => item.dimensionName),
      period1Data: tableData.value.map(item => getValue(item.period1)),
      period2Data: tableData.value.map(item => getValue(item.period2))
    };

    // 重新计算统计数据和渲染图表
    calculateStats();
    renderChart();
  }
});

// ==================== 方法定义 ====================

async function loadPeriodList() {
  try {
    // 传递足够大的pageSize获取所有调查期
    const response = await periodApi.getPeriodList({ pageSize: 100 });
    if (response.status === 'success') {
      periodList.value = response.data.list || [];
    }
  } catch (error) {
    console.error('加载调查期列表失败:', error);
    ElMessage.error('加载调查期列表失败');
  }
}

const createEmptyMetrics = () => ({
  enterpriseCount: 0,
  changeRatio: 0,
  constructionTotal: 0,
  investigationTotal: 0
});

async function fetchPeriodData(periodId, groupBy) {
  if (!periodId) return [];

  const params = {
    periodIds: [periodId],
    statuses: [4],
    ...(groupBy ? { groupBy } : {})
  };

  const response = await dataAnalysisApi.getTrendAnalysis(params);
  if (response.status !== 'success' || !Array.isArray(response.data)) {
    return [];
  }

  const raw = response.data || [];

  if (groupBy) {
    return raw.map(item => ({
      periodId,
      dimensionCode: item.dimensionCode ?? '__unknown__',
      dimensionName: item.dimensionName ?? '未知',
      enterpriseCount: item.enterpriseCount ?? 0,
      changeRatio: item.changeRatio ?? 0,
      constructionTotal: item.constructionTotal ?? 0,
      investigationTotal: item.investigationTotal ?? 0
    }));
  }

  const first = raw[0];
  if (!first) {
    return [{
      periodId,
      dimensionCode: '__all__',
      dimensionName: '全省汇总',
      enterpriseCount: 0,
      changeRatio: 0,
      constructionTotal: 0,
      investigationTotal: 0
    }];
  }

  return [{
    periodId,
    dimensionCode: '__all__',
    dimensionName: '全省汇总',
    enterpriseCount: first.enterpriseCount ?? 0,
    changeRatio: first.changeRatio ?? 0,
    constructionTotal: first.constructionTotal ?? 0,
    investigationTotal: first.investigationTotal ?? 0
  }];
}

async function handleQuery() {
  if (!queryParams.value.period1 || !queryParams.value.period2) {
    ElMessage.warning('请选择两个调查期');
    return;
  }

  loading.value = true;

  try {
    const groupBy = queryParams.value.groupBy;
    const period1Id = queryParams.value.period1;
    const period2Id = queryParams.value.period2;

    const [period1Data, period2Data] = await Promise.all([
      fetchPeriodData(period1Id, groupBy),
      fetchPeriodData(period2Id, groupBy)
    ]);

    const groupedMap = new Map();

    const attachData = (list, key) => {
      list.forEach(item => {
        const code = item.dimensionCode ?? '__unknown__';
        if (!groupedMap.has(code)) {
          groupedMap.set(code, {
            dimensionCode: code,
            dimensionName: item.dimensionName ?? '未知',
            period1: createEmptyMetrics(),
            period2: createEmptyMetrics()
          });
        }

        const target = groupedMap.get(code);
        target[key] = {
          enterpriseCount: item.enterpriseCount ?? 0,
          changeRatio: item.changeRatio ?? 0,
          constructionTotal: item.constructionTotal ?? 0,
          investigationTotal: item.investigationTotal ?? 0
        };
      });
    };

    attachData(period1Data, 'period1');
    attachData(period2Data, 'period2');

    // 根据展示模式计算差值和图表数据
    const getValue = (item) => {
      switch (displayMode.value) {
        case 'enterprise':
          return item.enterpriseCount;
        case 'position':
          return item.investigationTotal;
        case 'ratio':
        default:
          return item.changeRatio;
      }
    };

    tableData.value = Array.from(groupedMap.values()).map(row => ({
      ...row,
      diff: getValue(row.period2) - getValue(row.period1)
    }));

    chartData.value = {
      dimensions: tableData.value.map(item => item.dimensionName),
      period1Data: tableData.value.map(item => getValue(item.period1)),
      period2Data: tableData.value.map(item => getValue(item.period2))
    };

    calculateStats();
    await nextTick();
    renderChart();
    ElMessage.success('对比分析完成');
  } catch (error) {
    console.error('查询失败:', error);
    ElMessage.error('查询失败，请稍后重试');
  } finally {
    loading.value = false;
  }
}

function calculateStats() {
  if (!tableData.value.length) {
    stats.value = {
      period1: { value: 0 },
      period2: { value: 0 },
      trend: 0
    };
    return;
  }

  const calcAvg = (key) => {
    let total;
    switch (displayMode.value) {
      case 'enterprise':
        total = tableData.value.reduce((sum, row) => sum + (row[key].enterpriseCount ?? 0), 0);
        break;
      case 'position':
        total = tableData.value.reduce((sum, row) => sum + (row[key].investigationTotal ?? 0), 0);
        break;
      case 'ratio':
      default:
        total = tableData.value.reduce((sum, row) => sum + (row[key].changeRatio ?? 0), 0);
    }
    return tableData.value.length ? total / tableData.value.length : 0;
  };

  const avg1 = calcAvg('period1');
  const avg2 = calcAvg('period2');

  stats.value = {
    period1: { value: avg1 },
    period2: { value: avg2 },
    trend: avg2 - avg1
  };
}

function renderChart() {
  if (!chartRef.value) return;

  if (chartInstance && chartInstance.getDom() !== chartRef.value) {
    chartInstance.dispose();
    chartInstance = null;
  }

  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value);
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e5e5e7',
      textStyle: { color: '#1d1d1f' },
    },
    legend: {
      data: [period1Name.value, period2Name.value],
      top: 0,
      textStyle: { color: '#86868b', fontSize: 13 },
    },
    grid: {
      left: 240,
      right: '10%',
      bottom: '8%',
      top: '6%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      name: '变化占比(%)',
      axisLabel: { formatter: '{value}%', color: '#86868b' },
      splitLine: { lineStyle: { color: '#f5f5f7' } },
      axisLine: { lineStyle: { color: '#e5e5e7' } },
      nameTextStyle: { color: '#86868b' },
    },
    yAxis: {
      type: 'category',
      data: chartData.value.dimensions,
      axisLabel: {
        interval: 0,
        formatter: (value) => {
          if (!value) return '';
          const sanitized = String(value).trim();
          return `{value|${sanitized}}`;
        },
        rich: {
          value: {
            color: '#86868b',
            lineHeight: 32
          }
        },
        padding: [12, 0, 12, 0],
        margin: 18
      },
      axisLine: { lineStyle: { color: '#e5e5e7' } },
      axisTick: { show: false }
    },
    series: [
      {
        name: period1Name.value,
        type: 'bar',
        barGap: `${BAR_GAP_RATIO * 100}%`,
        barCategoryGap: `${BAR_CATEGORY_GAP_RATIO * 100}%`,
        barWidth: BAR_WIDTH,
        data: chartData.value.period1Data,
        itemStyle: { color: '#4f46e5', borderRadius: [0, 8, 8, 0] },
        label: {
          show: true,
          position: 'right',
          formatter: (params) => {
            const value = Number(params.value);
            if (displayMode.value === 'ratio') {
              if (Math.abs(value) < 0.005) return '0%';
              return `${value.toFixed(2)}%`;
            }
            return Math.round(value).toLocaleString('zh-CN');
          },
          color: '#1d1d1f',
          fontSize: 12,
          distance: 8
        },
      },
      {
        name: period2Name.value,
        type: 'bar',
        barGap: `${BAR_GAP_RATIO * 100}%`,
        barCategoryGap: `${BAR_CATEGORY_GAP_RATIO * 100}%`,
        barWidth: BAR_WIDTH,
        data: chartData.value.period2Data,
        itemStyle: { color: '#10b981', borderRadius: [0, 8, 8, 0] },
        label: {
          show: true,
          position: 'right',
          formatter: (params) => {
            const value = Number(params.value);
            if (displayMode.value === 'ratio') {
              if (Math.abs(value) < 0.005) return '0%';
              return `${value.toFixed(2)}%`;
            }
            return Math.round(value).toLocaleString('zh-CN');
          },
          color: '#1d1d1f',
          fontSize: 12,
          distance: 8
        },
      },
    ],
  };

  chartInstance.setOption(option);
  chartInstance.resize({ height: chartHeight.value });
}

function handleResize() {
  if (chartInstance) {
    chartInstance.resize();
  }
}

// ==================== 辅助函数 ====================

function getStatLabel() {
  const labels = {
    enterprise: '企业数量',
    position: '岗位数量',
    ratio: '失业率',
  };
  return labels[displayMode.value] || '数值';
}

function formatStatValue(value) {
  if (displayMode.value === 'ratio') {
    return typeof value === 'number' ? value.toFixed(2) + '%' : '0.00%';
  }
  return typeof value === 'number' ? Math.round(value).toLocaleString('zh-CN') : '0';
}

function formatTrendValue() {
  const absValue = Math.abs(stats.value.trend);
  if (displayMode.value === 'ratio') {
    return absValue.toFixed(2) + '%';
  }
  return Math.round(absValue).toLocaleString('zh-CN');
}

function getStatValueClass(value) {
  if (displayMode.value === 'ratio') {
    return 'stat-value negative';
  }
  return 'stat-value';
}

function getTrendClass() {
  if (displayMode.value === 'ratio') {
    return ['stat-value', stats.value.trend > 0 ? 'negative' : 'positive'];
  }
  return ['stat-value', stats.value.trend > 0 ? 'positive' : 'negative'];
}

function getDiffClass(diff) {
  if (displayMode.value === 'ratio') {
    return diff > 0 ? 'text-danger' : 'text-success';
  }
  return diff > 0 ? 'text-success' : 'text-danger';
}

function formatDiff(diff) {
  if (displayMode.value === 'ratio') {
    return (diff > 0 ? '+' : '') + diff.toFixed(2) + '%';
  }
  const sign = diff > 0 ? '+' : '';
  return sign + Math.round(diff).toLocaleString('zh-CN');
}
</script>

<style scoped lang="scss">
.comparison-analysis {
  /* Search Card */
  .search-card {
    background: #ffffff;
    border-radius: 16px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.02);
    padding: 24px;
    margin-bottom: 24px;
    border: 1px solid rgba(241, 245, 249, 1);
  }

  .search-section {
    display: flex;
    flex-wrap: wrap;
    gap: 24px;
    align-items: flex-end;
  }

  .filter-item {
    display: flex;
    flex-direction: column;
    gap: 8px;

    label {
      font-size: 13px;
      font-weight: 600;
      color: #64748b;
    }
  }

  .filter-actions {
    padding-bottom: 2px;
  }

  /* Inputs & Buttons */
  .custom-select {
    :deep(.el-input__wrapper) {
      border-radius: 8px;
      box-shadow: 0 0 0 1px #e2e8f0 inset;
      padding: 6px 12px;
      &.is-focus { box-shadow: 0 0 0 2px #818cf8 inset; }
    }
  }

  .btn-primary-theme {
    background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%);
    border: none;
    padding: 10px 24px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
    transition: all 0.2s;
    font-weight: 600;
    height: 40px;

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 8px 20px rgba(79, 70, 229, 0.3);
    }
  }

  /* Stats Grid */
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 24px;
    margin-bottom: 24px;
  }

  .stat-card {
    background: white;
    border-radius: 16px;
    padding: 32px 24px;
    border: 1px solid #e2e8f0;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.02);
    text-align: center;
    transition: all 0.2s;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 10px 20px -5px rgba(0, 0, 0, 0.05);
    }

    .stat-label {
      color: #64748b;
      font-size: 13px;
      font-weight: 600;
      text-transform: uppercase;
      margin-bottom: 12px;
      letter-spacing: 0.5px;
    }

    .stat-value {
      color: #0f172a;
      font-size: 32px;
      font-weight: 800;
      line-height: 1.2;

      &.positive { color: #10b981; }
      &.negative { color: #ef4444; }
    }
  }

  /* Chart & Table Cards */
  .chart-card, .table-card, .empty-card {
    background: #ffffff;
    border-radius: 24px;
    box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.03);
    border: 1px solid rgba(241, 245, 249, 1);
    margin-bottom: 24px;
    overflow: hidden;
  }

  .card-header {
    padding: 20px 24px;
    border-bottom: 1px solid #f1f5f9;
  }

  .card-title {
    font-size: 16px;
    font-weight: 700;
    color: #0f172a;
  }

  /* Chart Area */
  .chart-wrapper {
    padding: 24px;
  }

  .chart-container {
    width: 100%;
    min-height: 360px;
  }

  .legend {
    display: flex;
    justify-content: center;
    gap: 32px;
    margin-top: 24px;
    padding: 16px;
    background: #f8fafc;
    border-radius: 12px;
  }

  .legend-item {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 14px;
    font-weight: 600;
    color: #334155;
  }

  .legend-color {
    width: 12px;
    height: 12px;
    border-radius: 4px;
  }

  /* Table Styles */
  .modern-table {
    --el-table-border-color: #f1f5f9;
    --el-table-row-hover-bg-color: #f8fafc;
    --el-table-header-bg-color: #f8fafc;
  }

  .cell-primary-text {
    font-size: 14px;
    font-weight: 600;
    color: #0f172a;
  }

  .diff-value {
    font-weight: 700;
    font-variant-numeric: tabular-nums;
  }

  .text-danger { color: #ef4444; }
  .text-success { color: #10b981; }

  .empty-card {
    padding: 60px 0;
  }
}
</style>